<?php

function stackoverflow_get_comments()
{
    global $wpdb;
    $gmnow = gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
    $id = $wpdb->get_var($wpdb->prepare("select max(a.ID) from $wpdb->posts a where a.post_date_gmt>=%s and not exists(select 1 from $wpdb->comments b where b.comment_post_ID=a.ID) and a.post_type='joke' and a.post_status='publish' ", $gmnow));
    if ($id) {
        $item_id = $wpdb->get_var($wpdb->prepare("select post_title from $wpdb->posts where ID=%d", $id));
        if ($item_id) {
            add_post_meta($id, 'last-check-comments', time(), true) or update_post_meta($id, 'last-check-comments', time(), true);
            $i = 2;
            $total = $this->handleComments($item_id, $id);
            while ($i <= $total) {
                $this->handleComments($item_id, $id, $i);
                $i++;
            }
        }
    }
}

function handleComments($id, $post_id, $page = 1)
{
    $args = array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120);

    $content = wp_remote_get(sprintf('http://m2.qiushibaike.com/article/%d/comments?page=%d&count=50', $id, $page), $args);
    if (is_wp_error($content)) {
        error_log(sprintf("request %d,%d,%d failed", $id, $post_id, $page));
        return;
    }
    $comments = json_decode($content['body']);
    $results = array();

    foreach ($comments->items as $comment) {
        $item = array(
            'comment_post_ID' => $post_id,
            'comment_approved' => 1,
            'comment_parent' => 0,
        );
        $item['comment_author_IP'] = $comment->id;
        $item['comment_content'] = $comment->content;
        $item['comment_date'] = current_time('mysql');

        $user_id = 0;

        $user_id = get_user_id($comment->user);

        $item['user_id'] = $user_id;
        $results[] = $item;
    }
    $this->saveComments($results);
    return $comments->total;
}

function saveComments($comments)
{
    global $wpdb;
    foreach ($comments as $comment) {
        $temp = $wpdb->get_var($wpdb->prepare("select meta_id from $wpdb->commentmeta where meta_key='qiushibaike-comment-id' and meta_value=%s", $comment['comment_author_IP']));
        if (!$temp) {
            $id = wp_insert_comment($comment);
            add_comment_meta($id, 'qiushibaike-comment-id', $comment['comment_author_IP']);
        }
    }
}
